package com.example.ecs.core;

import java.util.HashMap;
import java.util.Map;

/**
 * Entity类表示游戏中的一个实体对象
 * 实体是游戏对象的唯一标识符，包含一个唯一的ID
 */
public class Entity {
    private static int nextId = 0;
    private final int id;
    private final Map<Class<? extends Component>, Component> components;
    
    public Entity() {
        this.id = nextId++;
        this.components = new HashMap<>();
    }
    
    public int getId() {
        return id;
    }
    
    public void addComponent(Component component) {
        // 获取组件的键类
        Class<? extends Component> keyClass = getComponentKeyClass(component);
        components.put(keyClass, component);
        component.setEntity(this);
    }
    
    public void removeComponent(Class<? extends Component> componentClass) {
        // 获取组件的键类
        Class<? extends Component> keyClass = getComponentKeyClassForClass(componentClass);
        components.remove(keyClass);
    }
    
    public <T extends Component> T getComponent(Class<T> componentClass) {
        // 获取组件的键类
        Class<? extends Component> keyClass = getComponentKeyClassForClass(componentClass);
        return  componentClass.cast(components.get(keyClass));
    }
    
    public boolean hasComponent(Class<? extends Component> componentClass) {
        // 获取组件的键类
        Class<? extends Component> keyClass = getComponentKeyClassForClass(componentClass);
        return components.containsKey(keyClass);
    }

    // 严格
    public boolean hasStrictComponent(Class<? extends Component> componentClass) {
        // 获取组件的键类
        Class<? extends Component> keyClass = getComponentKeyClassForClass(componentClass);
        Component component = components.get(keyClass);
        return component.getClass() == componentClass;
    }
    
    public Map<Class<? extends Component>, Component> getComponents() {
        return components;
    }
    
    /**
     * 获取组件实例的键类
     * 如果组件有ComponentKey注解，则使用注解中指定的类
     * 否则使用组件本身的类
     */
    private Class<? extends Component> getComponentKeyClass(Component component) {
        Class<? extends Component> componentClass = component.getClass();
        
        // 检查是否有ComponentKey注解
        if (componentClass.isAnnotationPresent(ComponentKey.class)) {
            ComponentKey annotation = componentClass.getAnnotation(ComponentKey.class);
            return annotation.value();
        }
        
        // 默认使用组件本身的类
        return componentClass;
    }
    
    /**
     * 获取组件类的键类
     * 如果组件类有ComponentKey注解，则使用注解中指定的类
     * 否则使用组件类本身
     */
    private Class<? extends Component> getComponentKeyClassForClass(Class<? extends Component> componentClass) {
        // 检查是否有ComponentKey注解
        if (componentClass.isAnnotationPresent(ComponentKey.class)) {
            ComponentKey annotation = componentClass.getAnnotation(ComponentKey.class);
            return annotation.value();
        }
        
        // 默认使用组件类本身
        return componentClass;
    }
}